// 🔒 离线存储管理器 - 核心数据缓存功能

export interface StorageItem {
  key: string;
  data: any;
  timestamp: string;
  expiry?: string;
  version: string;
}

export class OfflineStorage {
  private readonly VERSION = '1.0.0';
  private readonly PREFIX = 'pph_';

  /**
   * 保存数据到本地存储
   */
  set(key: string, data: any, expiryHours?: number): boolean {
    try {
      const item: StorageItem = {
        key,
        data,
        timestamp: new Date().toISOString(),
        version: this.VERSION
      };

      if (expiryHours) {
        const expiry = new Date();
        expiry.setHours(expiry.getHours() + expiryHours);
        item.expiry = expiry.toISOString();
      }

      const storageKey = this.PREFIX + key;
      localStorage.setItem(storageKey, JSON.stringify(item));
      
      return true;
    } catch (error) {
      console.error('❌ 本地存储失败:', error);
      return false;
    }
  }

  /**
   * 从本地存储获取数据
   */
  get<T = any>(key: string): T | null {
    try {
      const storageKey = this.PREFIX + key;
      const itemStr = localStorage.getItem(storageKey);
      
      if (!itemStr) return null;

      const item: StorageItem = JSON.parse(itemStr);

      // 检查版本兼容性
      if (item.version !== this.VERSION) {
        console.warn(`⚠️ 数据版本不匹配: ${item.version} vs ${this.VERSION}`);
        this.remove(key);
        return null;
      }

      // 检查是否过期
      if (item.expiry && new Date() > new Date(item.expiry)) {
        this.remove(key);
        return null;
      }

      return item.data as T;
    } catch (error) {
      console.error('❌ 本地存储读取失败:', error);
      return null;
    }
  }

  /**
   * 删除本地存储数据
   */
  remove(key: string): boolean {
    try {
      const storageKey = this.PREFIX + key;
      localStorage.removeItem(storageKey);
      return true;
    } catch (error) {
      console.error('❌ 本地存储删除失败:', error);
      return false;
    }
  }

  /**
   * 清空所有PPH相关的本地存储
   */
  clear(): boolean {
    try {
      const keys = Object.keys(localStorage);
      const pphKeys = keys.filter(key => key.startsWith(this.PREFIX));
      
      pphKeys.forEach(key => localStorage.removeItem(key));
      
      return true;
    } catch (error) {
      console.error('❌ 清空本地存储失败:', error);
      return false;
    }
  }

  /**
   * 获取存储使用情况
   */
  getStorageInfo(): {
    totalItems: number;
    totalSize: string;
    items: Array<{ key: string; size: string; timestamp: string }>;
  } {
    const keys = Object.keys(localStorage);
    const pphKeys = keys.filter(key => key.startsWith(this.PREFIX));
    
    let totalSize = 0;
    const items = pphKeys.map(key => {
      const value = localStorage.getItem(key) || '';
      const size = new Blob([value]).size;
      totalSize += size;
      
      try {
        const item: StorageItem = JSON.parse(value);
        return {
          key: key.replace(this.PREFIX, ''),
          size: this.formatBytes(size),
          timestamp: item.timestamp
        };
      } catch {
        return {
          key: key.replace(this.PREFIX, ''),
          size: this.formatBytes(size),
          timestamp: 'unknown'
        };
      }
    });

    return {
      totalItems: pphKeys.length,
      totalSize: this.formatBytes(totalSize),
      items
    };
  }

  /**
   * 检查存储空间
   */
  checkStorageQuota(): { used: number; available: number; percentage: number } {
    try {
      // 估算已使用空间
      let used = 0;
      for (const key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
          used += localStorage[key].length + key.length;
        }
      }

      // 大多数浏览器localStorage限制为5-10MB
      const estimated_limit = 5 * 1024 * 1024; // 5MB
      const available = estimated_limit - used;
      const percentage = (used / estimated_limit) * 100;

      return {
        used,
        available: Math.max(0, available),
        percentage: Math.min(100, percentage)
      };
    } catch {
      return { used: 0, available: 0, percentage: 0 };
    }
  }

  /**
   * 压缩存储数据
   */
  compressData(data: any): string {
    try {
      // 简单的数据压缩：移除空白字符
      return JSON.stringify(data).replace(/\s+/g, '');
    } catch {
      return JSON.stringify(data);
    }
  }

  /**
   * 解压存储数据
   */
  decompressData(compressedData: string): any {
    try {
      return JSON.parse(compressedData);
    } catch (error) {
      console.error('数据解压失败:', error);
      return null;
    }
  }

  private formatBytes(bytes: number): string {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  private showNotification(title: string, message: string, type: 'success' | 'warning' | 'error' | 'info'): void {
    // 延迟加载以避免直接依赖全局类型
    import('element-plus').then(mod => {
      const notify = (mod as any).ElNotification || (window as any).ElNotification;
      if (notify) {
        notify({ title, message, type, duration: 4500, position: 'top-right' });
      } else {
        console.log(`[${type}] ${title}: ${message}`);
      }
    }).catch(() => {
      console.log(`[${type}] ${title}: ${message}`);
    });
  }

  private async syncOfflineData(): Promise<void> {
    const offlineRecords = this.get<any[]>('offline_records') || [];
    
    if (offlineRecords.length === 0) return;

    try {
      const { pphService } = await import('../services/pphService');
      const result = await pphService.syncOfflineRecords(offlineRecords);

      if (result && (result as any).synced > 0) {
        this.remove('offline_records');
        this.showNotification(
          '数据同步完成',
          `成功同步 ${(result as any).synced} 条记录`,
          'success'
        );
      }
    } catch (error) {
      console.error('❌ 离线数据同步失败:', error);
      this.showNotification(
        '数据同步失败',
        '将在下次网络恢复时重试',
        'error'
      );
    }
  }

  /**
   * 销毁管理器
   */
  private reconnectTimer?: any;
  private healthCheckTimer?: any;

  destroy(): void {
    if (this.reconnectTimer) {
      clearInterval(this.reconnectTimer);
    }
    if (this.healthCheckTimer) {
      clearInterval(this.healthCheckTimer);
    }
  }
}

// 导出单例实例
export const offlineStorage = new OfflineStorage();
export default offlineStorage;
